﻿namespace EyeOpen.Dependency.Unity
{
    using System.Configuration;
    using System.Web;
    using Microsoft.Practices.Unity;
    using Microsoft.Practices.Unity.Configuration;

    public partial class UnityServiceContainer : IDependencyContainer
    {
        private IUnityContainer container;

        private IUnityContainer Container
        {
            get
            {
                if (this.container == null)
                {
                    this.container = this.GetContainer();
                }

                return this.container;
            }
        }

        private IUnityContainer GetContainer()
        {
            IUnityContainer unityContainer = new UnityContainer();
            this.ConfigureContainer(unityContainer);
            return unityContainer;
        }

        private void ConfigureContainer(IUnityContainer unityContainer)
        {
            ExeConfigurationFileMap unityExeConfigurationFileMap = new ExeConfigurationFileMap();
            if (HttpContext.Current != null)
            {
                unityExeConfigurationFileMap.ExeConfigFilename = HttpContext.Current.Server.MapPath("~/Unity.config");
            }
            else
            {
                unityExeConfigurationFileMap.ExeConfigFilename = "Unity.config";
            }
            
            Configuration unityConfiguration = ConfigurationManager.OpenMappedExeConfiguration(unityExeConfigurationFileMap, ConfigurationUserLevel.None);

            UnityConfigurationSection section = (UnityConfigurationSection)unityConfiguration.GetSection("unity");
            section.Containers.Default.Configure(unityContainer);
        }
    }
}
